import React, {Component} from 'react';
import {StyleSheet, Text, View,Image,
  ScrollView,Modal,TouchableWithoutFeedback,
  Dimensions,
  TouchableOpacity,RefreshControl
} from 'react-native';
import { Table, TableWrapper, Row, Rows, Col, Cols, Cell } from 'react-native-table-component';
import TopBar from '../bar/TopBar';
import SQLite from '../db/sqlite';
var {height,width} = Dimensions.get('window');
var sqLitec = new SQLite();
var db;
const ACCOUNT_TABLE = "t_account";//用户表
export default class Home extends Component{
  static navigationOptions = ({ navigation }) =>{
    const textStyle = {
			color:'white'
		}
		const viewStyle = {
			marginLeft: 15,
			flexDirection:'row',
			alignItems:'center'
    }
    const img = {
			width:20,
			height:20,
			marginRight:10,
			marginLeft:3
		}
    return{
      headerTitle:<TopBar title='记账' navigation = {navigation} 
                rightTitle='新增' rightPress={navigation.getParam('addPress')} />,
      headerLeft:(<TouchableOpacity activeOpacity={0.6} style={viewStyle} 
				onPress={navigation.getParam('yearPress')}>
				<Text style={textStyle}>{navigation.getParam('currYear')}</Text>
				<Image style={img} source={navigation.getParam('img')}/>
				</TouchableOpacity>),
    }
  };
  constructor(props){
    super(props);
    let years = [];
		years.push({year:0, text:'全部'})
		let currYear = new Date().getFullYear();
		for(let i=currYear; i>=2018; i--){
			years.push({year: i,text:i+' 年'})
		}
    this.state = ({
      years,
	  year: new Date().getFullYear(),
      visible: false,
      data:{},
      recordList:[],
      dataList:[],
      refreshing:true,
      tableHead: ['日期', '宽粉(斤)', '细粉(斤)', '总收益(元)'],
      widthArr: [width*0.3-20, width*0.2, width*0.2,width*0.3],
    })
  }
  componentWillMount(){
    if(!db){
      db = sqLitec.open();
      sqLitec.createTable();
    }
  }
  componentDidMount(){
    this._getData(new Date().getFullYear());
    this._statData(new Date().getFullYear());
    this.props.navigation.setParams({'currYear':new Date().getFullYear()+' 年'});
		this.props.navigation.setParams({'img':require('../images/icon_down.png')});
		this.props.navigation.setParams({'yearPress':this._yearPress});
    this.props.navigation.setParams({'addPress':this._addPress});
    
  }
  //年度选择
	_selectYear(year,text){
		this.props.navigation.setParams({'img':require('../images/icon_down.png')});
		this.props.navigation.setParams({'currYear': text});
		this.setState({
			visible:false,
			year:year
		},()=>{
			this._getData(year);
    this._statData(year);
		})
	}
  _yearPress =()=>{
		if(!this.state.visible){
			this.props.navigation.setParams({'img':require('../images/icon_up.png')});
		} else {
			this.props.navigation.setParams({'img':require('../images/icon_down.png')});
		}
		this.setState({
			visible:true
		})
	}
  _addPress=()=>{
    const {navigation} = this.props;
    if(navigation){
      navigation.push('addAccount',
        {
          id:'',
          callback: (data)=>{
            this.componentDidMount()
          }
        }
      );
    }
  }
  _onRefresh=()=>{
    this.setState({refreshing:true});
    this._getData(this.state.year);
    this._statData(this.state.year);
  }
  _statData(year){
    if(!db){
      db = sqLitec.open();
    }
    db.transaction((tx)=>{
      let sql = "select sum(val3) val3,sum(val5) val5,sum(val7) val7,sum(total_income) total_income,"+
      "sum(total_fund) total_fund from "+ACCOUNT_TABLE 
      let arr = []
      if(year != 0){
        sql += " where create_time like ? "
        arr = [year+ '%']
      }
      
      tx.executeSql(sql,arr ,(tx,result)=>{
        console.log('stat',result);
        var stat = result.rows.item(0);
        console.log('sta',stat);
        this.setState({
          data:stat,
        })
      },(err)=>{
        console.log(err)
      });
    },(error)=>{
      console.log(error);
    },()=>{

    });
  }
  _getData(year){
    if(!db){
      db = sqLitec.open();
    }
    db.transaction((tx)=>{
      let sql = "select * from "+ACCOUNT_TABLE;
      
      let arr = []
      if(year != 0){
        sql += " where create_time like ? ";
        arr = [year+ '%']
      }
      sql += " order by create_time desc"
      tx.executeSql(sql, arr, (tx,result)=>{
        var len = result.rows.length;
        var list = [];
        var data = [];
        for(let i=0; i<len; i++){
          var account = result.rows.item(i);
          let arr = [];
          arr.push(account.create_time);
          arr.push(account.val3);
          arr.push(account.val5);
          arr.push(account.total_income);
          //console.log(arr)
          data.push(account)
          list.push(arr);
        }
        this.setState({
          refreshing:false,
          recordList:list,
          dataList:data,
        })
        //console.log(this.state.recordList)
        //console.log('len',this.state.recordList.length)
      },(err)=>{
        console.log(err)
      });
    },(error)=>{
      console.log(error);
    },()=>{

    });
  }
  _alertIndex(index){

  }
  _edit(index){
    const {navigation} = this.props;
    if(navigation){
      navigation.push('addAccount',
        {
          id:this.state.dataList[index].id,
          callback: (data)=>{
            this.componentDidMount()
          }
        }
      );
    }
  }
  _renderYears(){
		let years = this.state.years;
		let views = [];
		const textStyle = {
			paddingTop:6,
			paddingBottom:6,
			paddingLeft:12,
      paddingRight:12,
      color: '#666',
      width: '100%',
		}
		for(let i=0; i<years.length; i++){
      let borStyle = {
        borderBottomWidth:StyleSheet.hairlineWidth,
        borderBottomColor:'#ccc',
      }
			views.push(
				<TouchableOpacity key={i} style={{alignItems:'center'}} 
					onPress={()=>{this._selectYear(years[i].year, years[i].text)}}>
					<Text style={[textStyle,i==years.length?null:borStyle]}>{years[i].text}</Text>
				</TouchableOpacity>
			)
		}
		return views;
	}
  render(){
    // const element = (data, index) => (
    //   <TouchableOpacity onPress={() => this._alertIndex(index)}>
    //     <View style={styles.btn}>
    //       <Text style={styles.btnText}>button</Text>
    //     </View>
    //   </TouchableOpacity>
    // );
    //<Rows data={this.state.recordList} textStyle={styles.text}/>
    console.log('log',this.state.recordList)
    var {data} = this.state;
    var totalWeight = data.val3+data.val5+data.val7
    return(
      <View style={styles.container}>
        <View style={styles.statView}>
          <StatView title="总重量" num={totalWeight} unit="斤"/>
          <StatView title="总收益" num={data.total_income} unit="元"/>
          <StatView title="总收入" num={data.total_fund} unit="元"/>
        </View>
        <Table borderStyle={{borderColor: 'transparent'}}>
            <Row data={this.state.tableHead} style={styles.head} textStyle={styles.text} widthArr={this.state.widthArr}/>
        </Table>
        <ScrollView style={styles.dataWrapper} showsVerticalScrollIndicator={false}
          refreshControl={
            <RefreshControl
              onRefresh={()=>{this._onRefresh()}}
              refreshing={this.state.refreshing}
            />
          }
          >
          <Table borderStyle={{borderColor: 'transparent'}}>
            {
              this.state.recordList.map((rowData, index) => (
                <TouchableOpacity onPress={()=>{this._edit(index)}} key={index} activeOpacity={0.6}>
                  <TableWrapper  style={[styles.row,{backgroundColor:(index%2==0)?'#FFF8D7':'#FFE6D9'}]} borderStyle={{borderWidth:0,borderColor:'transparent'}}> 
                    {
                      rowData.map((cellData, cellIndex) => (
                        <Cell  key={cellIndex}   style={{width:this.state.widthArr[cellIndex],justifyContent:'center',alignItems:'center'}}
                          data={cellData} textStyle={styles.text}/>
                      ))
                    }
                  </TableWrapper>
                </TouchableOpacity>
              ))
            }
          </Table>
        </ScrollView>
        <Modal  
          visible={this.state.visible}   
          transparent={true}  
          animationType='fade'   
          onRequestClose={() => {this.setState({visible:false})}}  
          style={{flex:1}} >
					<TouchableWithoutFeedback  onPress={()=>{
						this.setState({
							visible:false
						})
						this.props.navigation.setParams({'img':require('../images/icon_down.png')});
					}
						
						}>
						<View style={styles.modalBg}>
							<View style={styles.modalContent}>
								{this._renderYears()}
							</View>
						</View>
					</TouchableWithoutFeedback>
				</Modal>
      </View>
    )
  }
}
class StatView extends Component{
  render(){
    return(
      <View style={styles.rowStyle}>
        <Text style={styles.title}>{this.props.title}</Text>
        <Text style={styles.num}>{this.props.num}</Text>
        <Text style={styles.title}>{this.props.unit}</Text>
      </View>
    )
  }
}
const styles = StyleSheet.create({
  modalContent:{
		backgroundColor:'white',
		borderWidth:StyleSheet.hairlineWidth,
		borderColor:'#888',
		borderRadius:5,
		marginTop:50,
		marginLeft:10,
		height:'auto'
		
	},
  modalBg:{
		flex:1,
		backgroundColor:'rgba(0,0,0,0.2)',
		flexDirection:'row',
		justifyContent:'flex-start',
		alignItems:'flex-start'
	},
  container: { flex: 1, padding: 10, paddingTop: 30, backgroundColor: '#fff' },
  title:{
    fontSize:13,
    color:'#888',
  },
  num:{
    color:'#ED5100',
    fontSize:16,
    paddingLeft:5,
    paddingRight:5,
  },
  rowStyle:{
    flexDirection:'row',
    alignItems:'flex-end',
  },
  statView:{
    padding:10,
    flexDirection:'row',
    justifyContent:'space-around',
    alignItems:'center'
  },
  container: { flex: 1, padding: 10, paddingTop: 10, backgroundColor: '#fff' },
  head: { 
    height: 40, 
    backgroundColor: '#f0f0f0' ,
    justifyContent:'center',
    alignItems:'center'
  },
  text: { margin: 6 ,textAlign:'center'},
  row: { 
    flexDirection: 'row', 
    backgroundColor: '#FFF8D7',
    //borderWidth:StyleSheet.hairlineWidth,
    //borderColor:'red'
  },
  cellStyle:{
    // justifyContent:'center',
    // alignItems:'center',
  },
  btn: { width: 58, height: 18, backgroundColor: '#78B7BB',  borderRadius: 2 },
  btnText: { textAlign: 'center', color: '#fff' }
})